﻿var checkAll;
var checkAlls;
var checkpll;
var checkplls;
var vendorShow;
var Show;
var Fenye;
var vendorPage;
var close;
var closes;
var idsArray = [];
var vendorsArray = [];

//文档就绪函数
$(function () {
    generateDate();//自动生成时间
    fantian();//反填
});
// 初始化LayUI
layui.use(function () {
    var layer = layui.layer;
    var $ = layui.$;
    var util = layui.util;
    var form = layui.form;

    // 定义获取选中复选框值的函数
    function getCheckedCheckboxValues() {
        var checkedCheckboxValues = [];
        $("input[name='ckbproc']:checked").each(function () {
            checkedCheckboxValues.push($(this).val());
        });
        return checkedCheckboxValues;
        console.log(checkedCheckboxValues);
    }
    // 为文本框添加双击事件
    document.getElementById('vendorNo').ondblclick = function () {
        layer.open({
            type: 1,
            resize: false,
            shadeClose: true,
            title: '选择供应商',
            area: ['900px', '600px'],
            content: `<form class="layui-form" action="">
                         <div class="layui-form-item">
                             <div class="layui-inline">
                                 <label class="layui-form-label">供应商编号:</label>
                                 <div class="layui-input-block">
                                     <input type="text" id="vendorNo" name="vendorNo" placeholder="请输入" autocomplete="off" class="layui-input">
                                 </div>
                             </div>
                             <div class="layui-inline">
                                 <label class="layui-form-label">供应商名称:</label>
                                 <div class="layui-input-block">
                                     <input type="text" id="vendorName" name="vendorName" placeholder="请输入" autocomplete="off" class="layui-input">
                                 </div>
                             </div>
                             <div class="layui-inline">
                                 <div class="layui-btn-container">
                                     <button type="button" class="layui-btn layui-bg-blue" onclick="vendorPage()">
                                         <i class="layui-icon layui-icon-search"></i>搜索
                                     </button>
                                 </div>
                             </div>
                         </div>
                     </form>
                     <div>
                 <table class="layui-table">
                     <tr>
                         <th>
                             <input type="checkbox" id="checkAlls" onclick="checkAlls()" value="" />
                        </th>
                         <th>供应商编号</th>
                         <th>供应商名称</th>
                         <th>电话</th>
                         <th>传真</th>
                         <th>Email</th>
                         <th>联系人</th>
                         <th>地址</th>
                     </tr>
                     <tbody id="vendordata" name="vendordata"></tbody>
                 </table>
                     </div>
                     <div id="demo-laypage-layout"></div>
                     <div style="text-align:right;margin-top:30px">
                     <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="closePopupBtn" onclick="closes()">
                                         关闭
                                     </button>
                     <button type="button" class="layui-btn layui-bg-blue layui-btn-sm" >
                                         选择
                                     </button>
                     </div>`,
            success: function () {
                // 对弹层中的表单进行初始化渲染
                form.render();
                // 表单提交事件
                form.on('submit(demo-login)', function (data) {
                    var fields = data.field; // 获取表单字段值
                    return false; // 阻止默认 form 跳转
                });

                //获取复选框值
                var chooseButton = $(".layui-btn.layui-bg-blue:last");
                chooseButton.on('click', function () {
                    var checkedValues = getCheckedCheckboxValues();
                    if (checkedValues.length === 1) {

                        vendorsArray = checkedValues;
                        console.log("选中的复选框值:", checkedValues, vendorsArray);
                        layer.close(pageIndex);

                        //显示
                        layui.use('table', function () {
                            var form = layui.form;
                            var table = layui.table;

                            $.ajax({
                                url: '../Vonder/VenderFanShow',
                                type: 'post',
                                data: {
                                    vendorId: JSON.stringify(vendorsArray),
                                    token: localStorage.getItem("token")
                                },
                                success: function (res) {
                                    var res = JSON.parse(res)
                                    // res 是从后端获取到的 JSON 数据
                                    if (res.code === 0) {
                                        console.log(res.data);
                                        const vendorsData = res.data;
                                        // 将获取到的用户数据反填到表单相应字段
                                        $('#vendorNo').val(vendorsData.vendorNo);
                                        $('#vendorName').val(vendorsData.vendorName);
                                        $('#vendorContact').val(vendorsData.vendorContact);
                                        $('#vendorPhone').val(vendorsData.vendorPhone);

                                    } else {
                                        console.log(res.msg);
                                    }

                                },
                                error: function () {
                                    console.log('获取数据失败');
                                }
                            });
                        });

                        console.log("选中的复选框值:", vendorsArray);
                    } else {
                        layer.msg("最多选择一项");
                    }
                });

                //关闭弹窗
                closes = function () {
                    layer.closes(pageIndex);
                }
            }
        });
    };

    var pageIndex = 1;
    var pageSize = 6;
    var totalCount = 0;

    //弹窗显示
    vendorShow = function () {
        var model = JSON.stringify({
            vendorNo: $("#vendorNo").val() || "",
            vendorName: $("#vendorName").val() || "",
            vendorPhone: $("#vendorPhone").val() || "",
            vendorTypeId: $("#vendorTypeId").val() || 0,
            pageIndex: 1,
            pageSize: 6
        })
        $.ajax({
            url: '../Vonder/VenderShowDo',
            //async: false,//改为异步,
            type: 'post',
            data: {
                model: model,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var list = '';
                var res = JSON.parse(res);
                console.log(res)
                $(res).each(function () {
                    res += `
                         <tr>
                        <td>
                                <input type="checkbox" name="ckbproc" value="${this.vendorId}" />
                            </td>
                         <td>${this.vendorNo}</td>
                          <td>${this.vendorName}</td>
                          <td>${this.vendorPhone}</td>
                          <td>${this.vendorFax}</td>
                          <td>${this.vendorEmail}</td>
                          <td>${this.vendorContact}</td>
                          <td>${this.vendorAddress}</td>
                     </tr> `
                });
                $("#vendordata").html(res);
                totalCount = res.totalCount;
            }
        })
    }

    //分页
    vendorPage = function () {
        layui.use(function () {
            var laypage = layui.laypage;
            // 完整显示
            vendorShow()
            laypage.render({
                elem: 'demo-laypage-layout', // 元素 id
                count: totalCount, // 数据总数
                limit: pageSize,//2.设置默认分页大小
                limits: [6, 10, 15],//3.设置分页组件可选的分页大小
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
                jump: function (obj) {
                    console.log(obj);
                    pageIndex = obj.curr;
                    pageSize = obj.limit;
                    vendorShow();
                }
            });
        });
    }

    $(function () {
        vendorPage(); //分页
    });
    checkplls = function () {
        var checkedIds = $("input[name='ckbproc']:checked");//取所有选中的name=ckbproc的复选框集合
        var ids = [];//定义了一个数组,空的
        $(checkedIds).each(function (i, obj) {
            var id = $(obj).val();
            ids.push(id);//往数组里push数字,数字就是我们的商品id
        });

        console.log(ids)
    }
    checkAlls = function () {

        var checked = $("#checkAlls").prop("checked");  //取全选/反选 checkbox的选中状态值
        $("input[name='ckbproc']").prop("checked", checked);//把所有name=ckbproc的checkbox的选中状态赋值为 checked
        console.log(checked)
    }
});


//弹窗列表
layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;


    // 定义获取选中复选框值的函数
    function getCheckedCheckboxValues() {
        var checkedCheckboxValues = [];
        $("input[name='ckbproc']:checked").each(function () {
            checkedCheckboxValues.push($(this).val());
        });
        return checkedCheckboxValues;
        console.log(checkedCheckboxValues);
    }

    // 事件
    util.on('lay-on', {
        'test-page-custom': function () {
            layer.open({
                type: 1,
                area: ['950px', '600px'],
                resize: false,
                shadeClose: true,
                title: '选择产品',
                content: `
                            <form class="layui-form" action="">
                         <div class="layui-form-item">
                             <div class="layui-inline">
                                 <label class="layui-form-label">产品编号:</label>
                                 <div class="layui-input-block">
                                     <input type="text" id="productNo" name="productNo" placeholder="请输入" autocomplete="off" class="layui-input">
                                 </div>
                             </div>
                             <div class="layui-inline">
                                 <label class="layui-form-label">产品名称:</label>
                                 <div class="layui-input-block">
                                     <input type="text" id="productName" name="productName" placeholder="请输入" autocomplete="off" class="layui-input">
                                 </div>
                             </div>
                             <div class="layui-inline">
                                 <div class="layui-btn-container">
                                     <button type="button" class="layui-btn layui-bg-blue" onclick="Fenye()">
                                         <i class="layui-icon layui-icon-search"></i>搜索
                                     </button>
                                 </div>
                             </div>
                         </div>
                     </form>
                     <div>
                     <table class="layui-table">
                     <tr>
                         <th>
                             <input type="checkbox" id="checkAll" onclick="checkAll()" value="" />
                        </th>
                         <th>产品编号</th>
                         <th>产品名称</th>
                         <th>规格</th>
                         <th>类别</th>
                         <th>存储单位</th>
                         <th>包装类型</th>
                         <th>价格</th>
                         <th>重量</th>
                         <th>显示名</th>
                     </tr>
                     <tbody id="data"></tbody>
                 </table>
                     </div>
                     <div id="demo-laypage-layout"></div>
                     <div style="text-align:right;margin-top:30px">
                     <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="closePopupBtn" onclick="close()">
                                         关闭
                                     </button>
                     <button type="button" class="layui-btn layui-bg-blue layui-btn-sm" >
                                         选择
                                     </button>
                     </div>`,
                success: function () {
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field; // 获取表单字段值
                        return false; // 阻止默认 form 跳转
                    });

                    //获取复选框值
                    var chooseButton = $(".layui-btn.layui-bg-blue:last");
                    chooseButton.on('click', function () {
                        var checkedValues = getCheckedCheckboxValues();
                        if (checkedValues.length > 0) {
                            idsArray = checkedValues
                            console.log("选中的复选框值:", checkedValues, idsArray);
                            layer.close(index);
                            //显示
                            layui.use('table', function () {
                                var form = layui.form;
                                var table = layui.table;
                                $.ajax({
                                    url: '../Product/GetProductRangeModel',
                                    type: 'post',
                                    data: {
                                        productId: JSON.stringify(idsArray),
                                        token: localStorage.getItem("token")
                                    },
                                    success: function (res) {
                                        var res = JSON.parse(res)
                                        console.log(res.data)
                                        console.log(idsArray)
                                        // res 是从后端获取到的 JSON 数据
                                        if (res.code === 0) {
                                            console.log(res.data);
                                            table.render({
                                                elem: allocationProduct, // 对应 HTML 中表格的 id
                                                data: res.data, // 绑定获取到的数据
                                                cols: [[
                                                    { type: 'checkbox', fixed: 'left' },
                                                    { field: 'productName', title: '产品名称' },
                                                    { field: 'productNo', title: '产品编号' },
                                                    { field: 'productSpec', title: '规格' },
                                                    {
                                                        field: 'batch', edit: 'text',
                                                        title: '批次'
                                                    },
                                                    { field: 'price', title: '单价' },
                                                    { field: 'storageNum', edit: 'text', title: '入库数' },
                                                    { field: 'totalPrice', edit: 'text', title: '总价' },
                                                
                                                    { field: 'binLocationName', edit: 'text', title: '库位' },
                                                    {
                                                        field: '', title: '操作', width: 200, templet: function (d) {
                                                            return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-delete"><i class="layui-icon layui-icon-edit"></i>删除</a> ';
                                                        }
                                                    }
                                                ]],//==========
                                                done: function (res, curr, count) {
                                                    var options = this;

                                                    // 获取当前行数据 - 自定义方法
                                                    table.getRowData = function (tableId, elem) {
                                                        var index = $(elem).closest('tr').data('index');
                                                        return table.cache[tableId][index] || {};
                                                    };
                                                    // 展示数据 - 仅用于演示
                                                    var showData = function (data) {
                                                        return layer.msg('当前行最新数据：<br>' + util.escape(JSON.stringify(data)), {
                                                            offset: '16px',
                                                            anim: 'slideDown'
                                                        });
                                                    };
                                                }//===========

                                            })
                                        } else {
                                            console.log(res.msg);
                                        }
                                        // layui form select 事件
                                        form.on('select(select-demo)', function (obj) {
                                            var value = obj.value; // 获取选中项 value
                                            console.log(value)
                                            // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                                            var data = table.getRowData(options.id, obj.elem);
                                            // 更新数据中对应的字段
                                            data.binLocationName = value;
                                            // 显示当前行最新数据 - 仅用于示例展示
                                            showData(data);
                                        })//==========   
                                    },
                                    error: function () {
                                        console.log('获取数据失败');
                                    }
                                });
                            });

                            console.log("选中的复选框值:", checkedValues, idsArray);
                        } else {
                            layer.msg("请至少选择一项");
                        }

                    });

                    //关闭弹窗
                    close = function () {
                        layer.close(index);
                    }
                }

            });
            var index = 1;
            var size = 6;
            var tacount = 0;
            $(function () {
                Fenye();
            });
            //弹窗显示
            Show = function () {
                var productNo = $("#productNo").val();
                var productName = $("#productName").val();
                var manuNo = $("#manuNo").val();
                var vendorId = $("#vendorId").val();
                $.ajax({
                    url: '../Product/GEtProductShow',
                    async: false,//改为异步,
                    type: 'get',
                    data: {
                        productNo: productNo,
                        productName: productName,
                        manuNo: manuNo,
                        vendorId: vendorId,
                        index: index,
                        size, size,
                        token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        var list = '';
                        var parsedData = JSON.parse(res);
                        console.log(parsedData)
                        $(parsedData.data.list).each(function () {
                            list += `
                         <tr>
                        <td>
                                <input type="checkbox" name="ckbproc" value="${this.productId}" />
                            </td>
                         <td>${this.productNo}</td>
                          <td>${this.productName}</td>
                          <td>${this.productSpec}</td>
                          <td>${this.productTypeName}</td>
                          <td>${this.unitName}</td>
                          <td>${this.productWrap}</td>
                          <td>${this.price}</td>
                          <td>${this.productWeight}</td>
                                  <td>
                                     
                                    </td>
                     </tr> `
                        });
                        $("#data").html(list);
                        tacount = parsedData.data.tacount;
                    }
                })
            }

            //分页
            Fenye = function () {

                layui.use(function () {
                    var laypage = layui.laypage;
                    // 完整显示
                    Show()
                    laypage.render({
                        elem: 'demo-laypage-layout', // 元素 id
                        count: tacount, // 数据总数
                        limit: size,//2.设置默认分页大小
                        limits: [6, 10, 15],//3.设置分页组件可选的分页大小
                        layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
                        jump: function (obj) {
                            console.log(obj);
                            index = obj.curr;
                            size = obj.limit;
                            Show();
                        }
                    });
                });
            }

            checkpll = function () {
                var checkedIds = $("input[name='ckbproc']:checked");//取所有选中的name=ckbproc的复选框集合
                var ids = [];//定义了一个数组,空的
                $(checkedIds).each(function (i, obj) {
                    var id = $(obj).val();
                    ids.push(id);//往数组里push数字,数字就是我们的商品id
                });

                console.log(ids)
            }
            checkAll = function () {

                var checked = $("#checkAll").prop("checked");  //取全选/反选 checkbox的选中状态值
                $("input[name='ckbproc']").prop("checked", checked);//把所有name=ckbproc的checkbox的选中状态赋值为 checked
                console.log(checked)
            }
        }
    })
});

//自动生成时间
function generateDate() {
    var n = new Date();
    var ss = n.getFullYear() + (n.getMonth() + 1).toString().padStart(2, '0') +
        n.getDate().toString().padStart(2, '0') +
        n.getHours().toString().padStart(2, '0') +
        n.getMinutes().toString().padStart(2, '0') +
        n.getSeconds().toString().padStart(2, '0');
    $("#storageNo").val(ss);
    const year = n.getFullYear();
    const month = ("0" + (n.getMonth() + 1)).slice(-2);
    const day = ("0" + n.getDate()).slice(-2);
    $('#singleTime').val(year + "-" + month + "-" + day);
}

//反填
function fantian() {
    return new Promise((resolve, reject) => {
        // 获取要编辑的用户ID
        const procurementId = localStorage.getItem("procurementId");
        console.log(procurementId);
        if (procurementId) {
            // 发送AJAX请求获取数据
            $.ajax({
                type: "get",
                url: "/Purchase/GetFanProcurement",
                data: {
                    procurementId: procurementId,
                    token: localStorage.getItem("token")
                },
                success: (res) => {
                    try {
                        const { data } = JSON.parse(res);
                        console.log(data)
                        if (data) {
                            const { buyProductsData } = data;
                            var procurement = data;
                            console.log(procurement);
                            console.log(buyProductsData);
                            // 反填表单的函数
                            fillForm(procurement);

                            renderTable(buyProductsData);
                            resolve(procurement, buyProductsData);
                        } else {
                            layui.layer.msg(res.message, { icon: 2 });
                            reject(res.message);
                        }
                    } catch (e) {
                        console.error(e);
                        layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                        reject('数据解析失败');
                    }
                },
                error: () => {
                    layui.layer.msg('获取用户信息失败，请稍后重试', { icon: 2 });
                    reject('获取用户信息失败');
                }
            });
        } else {
            reject('未获取到有效的仓库ID');
        }
    });
}
var obj = {
    procurementId: 0,
    procurementState: '',
    isRecorded: '',
    isReturn: '',
    returnsNum: '',
    returnNo: '',
    createName: '',
    createTime: '',
    updateName: '',
    deleteName: '',
    deleteTime: ''
};
// 反填表单的函数
function fillForm(procurement) {
    $('#storageType').val(procurement.procurementTypeName);
    layui.form.render('select')
    $('#associateNumber').val(procurement.associateNumber);
    $('#vendorNo').val(procurement.vendorNo);
    $('#vendorName').val(procurement.vendorName);
    $('#vendorContact').val(procurement.procurementPerson);
    $('#vendorPhone').val(procurement.procurementPhone);
    $('#singleMaker').val(procurement.singleMaker);
    const date = new Date(procurement.singleTime);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    $('#singleTime').val(year + "-" + month + "-" + day);
    $('#storageRemarks').val(procurement.procurementRemark);

    obj.procurementId = procurement.procurementId
    obj.procurementState = procurement.procurementState
    obj.isRecorded = procurement.isRecorded
    obj.isReturn = procurement.isReturn
    obj.returnsNum = procurement.returnsNum
    obj.returnNo = procurement.returnNo
    obj.createName = procurement.createName
    obj.createTime = procurement.createTime
    obj.updateName = procurement.updateName
    obj.deleteName = procurement.deleteName
    obj.deleteTime = procurement.deleteTime
    console.log(obj)
    // 重新渲染表单元素（如果有）
    //form.render();
}
// 渲染表格的函数
function renderTable(buyProductsData) {
    console.log(buyProductsData);
    var buyProductsId = buyProductsData.buyProductsId
    // 渲染表格的函数
    layui.use('table', function () {
        var table = layui.table;
        if (buyProductsData) {
            var inst = table.render({
                elem: '#allocationProduct', // 对应HTML中表格的id
                data: buyProductsData, // 绑定获取的数据
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'productName', title: '产品名称' },
                    { field: 'productNo', title: '产品编号' },
                    { field: 'productSpec', title: '规格' },
                    {
                        field: 'batch', edit: 'text',
                        title: '批次'
                    },
                    { field: 'price', title: '单价' },
                    { field: 'storageNum', edit: 'text', title: '入库数' },
                    { field: 'totalPrice', edit: 'text', title: '总价' },

                    { field: 'binLocationName', edit: 'text', title: '库位' },
                ]],
            });
        }
    });
}

// 表单提交事件
layui.use(['layer', 'form', 'util', 'table'], function () {
    var layer = layui.layer;
    var $ = layui.jquery;
    var form = layui.form;
    var util = layui.util;
    var table = layui.table;

    form.on('submit(demo2)', function (data) {
        var field = data.field;
        var checkStatus = table.checkStatus('allocationProduct');
        field.storageProducts = checkStatus.data.map(function (item) {
            return item;
        });
        console.log(field);//field.products
        // 显示填写结果，仅作演示用
        $.ajax({
            url: '/Warehouse/GetAddStorage',
            type: 'post',
            data: {
                field: field,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(field);
                console.log(res);
                if (res.code == 0) {
                    layer.alert("添加成功");
                    //跳转页面
                    setTimeout(function () {
                        location.href = '/Warehouse/StorageShow'
                    }, 2000);
                } else {
                    layer.alert("添加失败");
                }
            }
        });

        return false; // 阻止默认 form 跳转
    });
});

// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}